package cn.stimd.spring.transaction.support;

import cn.stimd.spring.transaction.TransactionException;

import java.util.Date;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public abstract class ResourceHolderSupport implements ResourceHolder{
    private boolean rollbackOnly = false;
    private Date deadline;
    private boolean isVoid = false;

    public void setRollbackOnly() {
        this.rollbackOnly = true;
    }

    public boolean isRollbackOnly() {
        return this.rollbackOnly;
    }

    public void setTimeoutInSeconds(int seconds) {
        this.deadline = new Date(System.currentTimeMillis() + seconds * 1000L);
    }

    public Date getDeadline() {
        return this.deadline;
    }

    public int getTimeToLiveInSeconds() {
        long timeToLive = this.deadline.getTime() - System.currentTimeMillis();
        double diff = ((double) timeToLive) / 1000;
        int secs = (int) Math.ceil(diff);
        checkTransactionTimeout(secs <= 0);
        return secs;
    }

    private void checkTransactionTimeout(boolean deadlineReached) throws TransactionException {
        if (deadlineReached) {
            setRollbackOnly();
            throw new TransactionException("事务超时：最后期限为" + this.deadline);
        }
    }

    public void clear() {
        this.rollbackOnly = false;
        this.deadline = null;
    }

    @Override
    public void reset() {
        clear();
//        this.referenceCount = 0;
    }

    @Override
    public void unbound() {
        this.isVoid = true;
    }

    @Override
    public boolean isVoid() {
        return this.isVoid;
    }
}
